<template>
  <div v-loading="loading" class="exam-container">
    <div class="content-container">
      <px-row :gutter="16">
        <px-col :span="18">
          <div class="timer flex-center">
            <CountDownIcon />
            <span class="count-time" style="display: none">{{ countTime }}</span>
            <span class="count-time">{{ remainingTime }}</span>
          </div>
          <div class="subject-content">
            <px-scrollbar>
              <div v-for="(item, index) in subjectList" :id="`subject${index}`" :key="item.id" class="subject">
                <div class="mg-b-8 flex-center">
                  <span class="subject-type">[{{ item.questionTypeName }}]</span>
                  <span class="subject-title" v-html="item.questionName" />
                </div>
                <px-radio-group v-if="item.questionType === 'S'" v-model="item.answer">
                  <div v-for="option in item.options" :key="option.optionName" class="option">
                    <px-radio :label="option.optionName"> {{ option.optionName }}. <span v-html="option.optionContent" /> </px-radio>
                  </div>
                </px-radio-group>
                <px-radio-group v-if="item.questionType === 'T'" v-model="item.answer">
                  <div v-for="option in item.options" :key="option.optionName" class="option">
                    <px-radio :label="option.optionContent"><span v-html="option.optionContent" /> </px-radio>
                  </div>
                </px-radio-group>
                <px-checkbox-group v-if="item.questionType === 'M'" v-model="item.answer">
                  <div v-for="option in item.options" :key="option.optionName" class="option">
                    <px-checkbox :label="option.optionName"> {{ option.optionName }}. <span v-html="option.optionContent" /> </px-checkbox>
                  </div>
                </px-checkbox-group>
              </div>
            </px-scrollbar>
          </div>
        </px-col>
        <px-col :span="6">
          <div class="right-content">
            <span
              v-for="(item, index) in subjectList"
              :key="item.id"
              :class="['order-bar', item.answer.length > 0 ? 'actived' : '']"
              @click="scrollToSubject(index)"
            >
              {{ index + 1 }}
            </span>
            <div class="answer-info">
              <div class="flex-center"><span class="order-bar actived" />已答{{ answeredNum }}题</div>
              <div class="flex-center" style="margin-left: 32px"><span class="order-bar" />未答{{ subjectList.length - answeredNum }}题</div>
            </div>
          </div>
        </px-col>
      </px-row>
    </div>
    <div class="page-footer">
      <px-button @click="exit">退出</px-button>
      <px-button type="primary" @click="submitExam">提交</px-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, onBeforeUnmount, watch, computed } from "vue";
import { useRouter } from "vue-router";
import { timeToSeconds, getNow, formateSeconds } from "@/views/all/knowledge/trainManage/utils";
import { PxMessage, PxMessageBox } from "px-ui";
import CountDownIcon from "@/assets/svg/knowledge/countDown.svg?component";
import { getExamAPI, submitExamAPI } from "@/api/knowledge/examManage";
import dayjs from "dayjs";

defineOptions({
  name: "ALL_KNOWLEDGE_EXAMMANAGE_EXAM"
});

const router = useRouter();

const state = reactive({
  loading: false,
  countTime: "00:00:00",
  remainingTime: "",
  paramData: {},
  examData: {},
  subjectList: [],
  startTime: ""
});
const { loading, countTime, remainingTime, paramData, examData, subjectList, startTime } = toRefs(state);

onMounted(() => {
  state.paramData = router.currentRoute.value.query;
  getExam();
});

const answeredNum = computed(() => {
  return state.subjectList.filter(item => item.answer.length > 0).length;
});

const getExam = async () => {
  try {
    state.loading = true;
    const params = {
      examId: state.paramData.examId,
      examineeId: state.paramData.examineeId
    };
    state.loading = true;
    const res = await getExamAPI(params);
    state.examData = res;
    state.subjectList = res.questions;
    state.subjectList.forEach(item => {
      item.answer = item.questionType === "M" ? [] : "";
    });
    countRemaining();
    countTimer();
    state.startTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

let timer;
const countTimer = () => {
  let start_time = new Date();
  timer = setInterval(() => {
    let millisecond = new Date() - start_time;
    let h = Math.floor(millisecond / (60 * 60 * 1000));
    h = h < 10 ? "0" + h : h;
    let min = Math.floor((millisecond % (60 * 60 * 1000)) / (60 * 1000));
    min = min < 10 ? "0" + min : min;
    let sec = Math.floor(((millisecond % (60 * 60 * 1000)) % (60 * 1000)) / 1000);
    sec = sec < 10 ? "0" + sec : sec;
    state.countTime = h + ":" + min + ":" + sec;
  }, 1000);
};

// 正计时
watch(
  () => state.countTime,
  val => {
    if (timeToSeconds(val) === Number(state.examData.duration) * 60) {
      clearInterval(timer);
      PxMessageBox.confirm("考试结束", "提示", {
        confirmButtonText: "确定",
        showCancelButton: false,
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: "warning"
      })
        .then(() => {
          submitExam();
        })
        .catch(() => {});
    }
  }
);

// 倒计时
let remainTimer;
const countRemaining = () => {
  let t = Number(state.examData.duration) * 60;
  remainTimer = setInterval(() => {
    if (t > 0) {
      t--;
      state.remainingTime = formateSeconds(t);
    } else {
      clearInterval(remainTimer);
    }
  }, 1000);
};

// 滚动到锚点
const scrollToSubject = index => {
  document.querySelector(`#subject${index}`).scrollIntoView({ behavior: "smooth" });
};

// 提交考试
const userInfo = JSON.parse(localStorage.getItem("userInfo"));
const submitExam = async () => {
  try {
    state.loading = true;
    const params = {
      examineeId: userInfo.userId,
      examId: state.examData.examId,
      startTime: state.startTime,
      endTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      questions: state.subjectList.map(item => {
        return {
          questionId: item.questionId,
          questionType: item.questionType,
          questionName: item.questionName,
          examineeId: userInfo.userId,
          examId: state.examData.examId,
          choice: item.questionType === "M" ? item.answer.toString() : item.answer
        };
      })
    };
    await submitExamAPI(params);
    // 跳转到考试结果页
    router.push({
      path: "/all/knowledge/examManage/myExam/examResult",
      query: {
        examId: state.examData.examId,
        examineeId: userInfo.userId
      }
    });
    PxMessage.success("提交成功");
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 退出
const exit = () => {
  PxMessageBox.confirm("确定退出考试吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      router.push({
        path: "/all/knowledge/examManage/myExam"
      });
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/examManage/scss/common.scss");

.exam-container {
  position: relative;

  .content-container {
    width: 100%;
    height: calc(100vh - 230px);

    .timer {
      margin-bottom: 32px;
    }

    .subject-content {
      height: calc(100vh - 280px);
      overflow-y: auto;
    }

    .subject {
      margin-bottom: 32px;

      .subject-type {
        margin-right: 8px;
        color: #999;
      }

      .subject-title {
        font-size: 16px;
        font-weight: 700;
      }

      .option {
        margin-left: 70px;
      }
    }

    .right-content {
      position: relative;
      height: calc(100vh - 230px);
      padding: 16px;
      border: 1px solid #dfdfdf;
      border-radius: 4px;

      .order-bar {
        display: inline-block;
        width: 40px;
        height: 40px;
        margin: 0 16px 16px 0;
        line-height: 40px;
        text-align: center;
        background: #dfdfdf;
      }

      .actived {
        color: #fff;
        background: #3b82f6;
      }

      .answer-info {
        position: absolute;
        bottom: 0;
        left: 16px;
        display: flex;
        align-items: center;
      }
    }
  }

  :deep(.px-radio-group) {
    display: block;
  }

  :deep(.px-radio .px-radio__label) {
    display: flex;
  }

  :deep(.px-checkbox .px-checkbox__label) {
    display: flex;
  }

  .page-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 60px;
    box-shadow: 0 0 8px #00000021;
  }
}

.count-time {
  margin-left: 8px;
  font-size: 24px;
  font-weight: bold;
}
</style>
